<?php

namespace app\admin\controller\dept;

use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\Exception;

/**
 * 
 *
 * @icon fa fa-file
 */
class Dept extends Backend
{

    /**
     * Dept模型对象
     */
    protected $model = null;
    protected $noNeedRight=["lists","roletree"];
    protected $noNeedLogin=["lists","roletree"];
    public $grouplist;
    public $groupdata;


    public function _initialize()
    {
        parent::_initialize();

        $this->model = model('Dept');
        $tree = Tree::instance();
        $tree->init(collection($this->model->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $pid=185;
        $arr = $tree->getTreeList($tree->getTreeArray($pid), 'name');
        $filteredData=array();
        for($i=0;$i<count($arr);$i++) {
            $v=$arr[$i];
            $filteredData[] = [
                'id' => $v['id'],
                'parent' => $v['pid'] ? $v['pid'] : '#',
                'text' => $v['name'],
                'type' => $v['type'],
                'status' => $v['status'],
            ];
        }
        $this->grouplist=$filteredData;
        $groupdata=[];
        foreach ($filteredData as $k=>$v){
            $groupdata[]=array(
                "id"=>$v["id"],
                "name"=>$v["text"],
            );
        }
        $this->groupdata=$groupdata;
        $this->view->assign("groupdata", $groupdata);
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $list = $this->grouplist;
            $total = count($list);
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }


    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
             if ($params) {
                $this->model->create($params);
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            $row->save($params);
            $this->success();
            return;
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $ids = explode(',', $ids);
            $count = $this->model->where('id', 'in', $ids)->delete();
            if ($count) {
                $this->success();
            }
        }
        $this->error();
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 组别禁止批量操作
        $this->error();
    }

    /**
     * 读取角色权限树
     *
     * @internal
     */
    public function roletree()
    {
        $this->view->assign("groupdata", $this->groupdata);
    }

    public function lists($ids = NULL){
        $where="where 1=1";
        if($_SESSION['think']['admin']['group_id']!=1){
            //$where.=" and city_id='{$_SESSION['think']['admin']['city_id']}'";
        }
        $page=1;
        $pagesize=50;
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10 : $pagesize;
                if ($keyValue != "") {
                    $nn=preg_split("/\,/",$keyValue);
                    for($i=0;$i<count($nn);$i++) {
                        $where.= " and $keyField='{$nn[$i]}'";
                    }
                }
            }
        }
        $sql="select id,pid,name,title,status from dev002_gxyusheng.fa_dept $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
        $list = db()->query($sql);
        $tree = Tree::instance();
        $tree->init($list, 'pid');
        $list = $tree->getTreeList($tree->getTreeArray(0), 'name');
        for($i=0;$i<count($list);$i++){
            $list[$i]['name']=preg_replace("/\&nbsp\;/"," ",$list[$i]['name']);
        }
        $total = db()->query("select count(1) as c from  dev002_gxyusheng.fa_dept $where")[0];
        echo json_encode(array("list" => $list, "total" => $total['c']));
        exit;
    }

}
